package com.vanvalt.payhui.modules.pay.web;

import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vanvalt.payhui.modules.pay.entity.Agent;
import com.vanvalt.payhui.modules.pay.entity.Pos;
import com.vanvalt.payhui.modules.pay.entity.PosApply;
import com.vanvalt.payhui.modules.pay.entity.UserShare;
import com.vanvalt.payhui.modules.pay.service.AgentService;
import com.vanvalt.payhui.modules.pay.service.PosApplyService;
import com.vanvalt.payhui.modules.pay.service.PosService;
import com.vanvalt.payhui.modules.pay.service.UserService;
import com.vanvalt.payhui.modules.pay.service.UserShareService;
import com.vanvalt.payhui.util.constat.Constant;
import com.vanvalt.payhui.util.mob.sms.spi.SmsWebApiKit;
import com.vanvalt.payhui.util.random.ShareCode;

/**
 * APP访问页面
 * @author Xiaoyang
 *
 */
@Controller
@RequestMapping(value = "${frontPath}/pay")
public class AppController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private PosService posService;
	@Autowired
	private PosApplyService posApplyService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private UserShareService userShareService;
	
	/**
	 * POS信息预览
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "pos/view")
	public String view(@RequestParam(required=false) String id, Model model) {
		
		Pos pos = null;
		if(StringUtils.isNotBlank(id)){
			pos = posService.get(id);
		}else{
			pos = new Pos();
		}
		
		model.addAttribute("pos", pos);
		return "mobile/modules/pay/posView";
	}
	
	/**
	 * POS机详情
	 * @param id
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "pos/detail")
	public String detail(@RequestParam(required=false) String id, @RequestParam(required=false) String uid, Model model) {
		
		Pos pos = null;
		if(StringUtils.isNotBlank(id)){
			pos = posService.get(id);
		}else{
			pos = new Pos();
		}
		
		model.addAttribute("pos", pos);
		model.addAttribute("uid", uid);
		
		return "mobile/modules/pay/posDetail";
	}
	
	/**
	 * 申请POS机-移动端
	 * @param id
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "pos/toapply")
	public String apply(@RequestParam(required=false) String id, @RequestParam(required=false) String uid, Model model) {
		
		Pos pos = null;
		if(StringUtils.isNotBlank(id)){
			pos = posService.get(id);
		}else{
			pos = new Pos();
		}
		
		model.addAttribute("pos", pos);
		model.addAttribute("uid", uid);
		
		return "mobile/modules/pay/posApply";
	}
	
	/**
	 * POS机申请提交-移动端
	 * @param posId
	 * @param userId
	 * @param name
	 * @param phone
	 * @param provinceCode
	 * @param provinceName
	 * @param cityCode
	 * @param cityName
	 * @param districtCode
	 * @param districtName
	 * @return
	 * @throws JSONException
	 */
	@ResponseBody
	@RequestMapping(value = "pos/applySubmit")
	public String applySubmit(@RequestParam(required=false) String posId,
			@RequestParam(required=false) String userId,
			@RequestParam(required=false) String name,
			@RequestParam(required=false) String phone,
			@RequestParam(required=false) String provinceCode,
			@RequestParam(required=false) String provinceName,
			@RequestParam(required=false) String cityCode,
			@RequestParam(required=false) String cityName,
			@RequestParam(required=false) String districtCode,
			@RequestParam(required=false) String districtName) throws JSONException{
		
		JSONObject json = new JSONObject();
		
		if(posId == null || "".equals(posId)){
			json.put("success", false);
		} else {
			
			if(userId == null || "".equals(userId)){
				json.put("success", false);
			} else {
				User user = userService.get(userId);
				if(user != null){
					PosApply posApply = new PosApply();
					
					posApply.setPosId(posId);
					posApply.setUserId(userId);
					posApply.setName(name);
					posApply.setPhone(phone);
					posApply.setProvinceCode(provinceCode);
					posApply.setProvinceName(provinceName);
					posApply.setCityCode(cityCode);
					posApply.setCityName(cityName);
					posApply.setDistrictCode(districtCode);
					posApply.setDistrictName(districtName);
					posApply.setCreateBy(user);
					posApply.setStatus(Constant.APPLY_STATUS_PENDING); // 提交申请状态：待定
					
					posApplyService.save(posApply);
					json.put("success", true);
				}
				
			}
		}
		
		return json.toString();
	}
	
	/**
	 * 申请代理-移动端
	 * @param id
	 * @param uid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "agent/toapply")
	public String agentApply(@RequestParam(required=false) String id, @RequestParam(required=false) String uid, Model model) {
		
		Agent agent = null;
		if(StringUtils.isNotBlank(id)){
			agent = agentService.get(id);
		}else{
			agent = new Agent();
		}
		
		model.addAttribute("agent", agent);
		model.addAttribute("uid", uid);
		
		return "mobile/modules/pay/agentApply";
	}
	
	/**
	 * 代理申请提交-移动端
	 * @param userId
	 * @param company
	 * @param realName
	 * @param qq
	 * @param email
	 * @param phone
	 * @param provinceCode
	 * @param provinceName
	 * @param cityCode
	 * @param cityName
	 * @param districtCode
	 * @param districtName
	 * @return
	 * @throws JSONException
	 */
	@ResponseBody
	@RequestMapping(value = "agent/applySubmit")
	public String agentApplySubmit(
			@RequestParam(required=false) String userId,
			@RequestParam(required=false) String company,
			@RequestParam(required=false) String realName,
			@RequestParam(required=false) String qq,
			@RequestParam(required=false) String email,
			@RequestParam(required=false) String phone,
			@RequestParam(required=false) String provinceCode,
			@RequestParam(required=false) String provinceName,
			@RequestParam(required=false) String cityCode,
			@RequestParam(required=false) String cityName,
			@RequestParam(required=false) String districtCode,
			@RequestParam(required=false) String districtName) throws JSONException{
		
		JSONObject json = new JSONObject();
		
		if(userId == null || "".equals(userId)){
			json.put("success", false);
		} else {
			
			User user = userService.get(userId);
			if(user != null){
				Agent agent = new Agent();
				agent.setUserId(userId);
				agent.setUserName(user.getName());
				agent.setCompany(company);
				agent.setRealName(realName);
				agent.setEmail(email);
				agent.setQq(qq);
				agent.setPhone(phone);
				agent.setProvinceCode(provinceCode);
				agent.setProvinceName(provinceName);
				agent.setCityCode(cityCode);
				agent.setCityName(cityName);
				agent.setDistrictCode(districtCode);
				agent.setDistrictName(districtName);
				agent.setStatus(Constant.APPLY_STATUS_PENDING); // 申请提交状态：待定
				agent.setCreateBy(user);
				
				agentService.save(agent);
				
				json.put("success", true);
			} else {
				json.put("success", false);
			}
		}
		
		return json.toString();
	}
	
	/**
	 * 邀请注册
	 * @param ic
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "inviteReg")
	public String inviteReg(@RequestParam(required=false) String ic, Model model) {
		
		model.addAttribute("inviteCode", ic); // inviteCode
		
		return "mobile/modules/pay/register";
	}
	
	/**
	 * 邀请注册提交
	 * @param inviteCode
	 * @param name
	 * @param phone
	 * @param password
	 * @return
	 * @throws JSONException
	 */
	@ResponseBody
	@RequestMapping(value = "inviteRegSubmit")
	public String inviteRegSubmit(
			@RequestParam(required=false) String inviteCode,
			@RequestParam(required=false) String name,
			@RequestParam(required=false) String phone,
			@RequestParam(required=false) String code,
			@RequestParam(required=false) String password) throws JSONException{
		
		JSONObject json = new JSONObject();
		
		boolean existUser = false;
		boolean invalidCode = false;
			
		if(phone == null || "".equals(phone)){
			json.put("success", false);
		} else {
			User user = systemService.getUserByLoginName(phone);
			if(user != null){ // 该手机号已注册过
				json.put("success", false);
				existUser = true;
				json.put("existUser", existUser);
			} else {
				
				try {
					/**
					 * 通过审核的任一个应用的appkey
					 */
					String appkey = Constant.APP_KEY_MAP.get("1").toString();
					
					/**
					 * http://wiki.mob.com/smssdk2-0-web-api/
					 */
					// 发送手机验证码
					SmsWebApiKit apiKit = new SmsWebApiKit(appkey);
					
					String result = apiKit.checkcode(phone, Constant.SMS_DEFAULT_ZONE, code);
					
					JSONObject obj = new JSONObject(result);
					int status = (Integer) obj.get("status");
					
					if(status == 200){
						
					} else {
						json.put("success", false);
						invalidCode = true;
						json.put("invalidCode", invalidCode);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(!invalidCode){ // 手机验证码验证通过
					
					if(inviteCode != null && !"".equals(inviteCode)){
						
						User newUser = new User();
						
						newUser.setCompany(this.getCompany());
						newUser.setOffice(this.getOffice());
						newUser.setLoginName(phone);
						newUser.setPassword(SystemService.entryptPassword(password));
						newUser.setName(name);
						newUser.setPhone(phone);
						newUser.setMobile(phone);
						newUser.setUserType(Constant.USER_TYPE_COMMON); // 普通用户
						newUser.setNo(Constant.USER_NO_DEFAULT); // 默认用户工号
						newUser.setRemarks("普通用户");
						// 普通用户默认角色列表
						List<Role> roleList = this.getRoleListByEn(Constant.USER_ROLE_DEFAULT);
						newUser.setRoleList(roleList);
						
						// 根据邀请码获取邀请人tid
						long lTid = ShareCode.codeToId(inviteCode.toLowerCase());
						
						User userParam = new User();
						userParam.setTid(new Long(lTid).intValue());
						// 根据tid查询邀请人信息
						User inviter = userService.findUserByTid(userParam);
						
						if(inviter == null){ // 邀请码不合法
							// 邀请码不合法，则不保存邀请注册记录
							
							/*json.put("success", false);
							invalidCode = true;
							json.put("invalidCode", invalidCode);*/
							newUser.setCreateBy(new User("1"));
							newUser.setUpdateBy(new User("1"));
						} else {
							newUser.setCreateBy(inviter);
							newUser.setUpdateBy(inviter);
						}
						
						// 保存用户信息
						systemService.saveUser(newUser);
						
						// 更新用户邀请码
						int tid = newUser.getTid();
						String newUserInviteCode = ShareCode.toSerialCode(tid);
						newUser.setInviteCode(newUserInviteCode.toUpperCase());
						systemService.updateUserInviteCode(newUser);
						
						// 保存邀请注册记录
						if(inviter != null){
							
							UserShare userShare = new UserShare();
							userShare.setUserId(newUser.getId()); // 被邀请（注册）人ID
							userShare.setName(name);
							userShare.setPhone(phone);
							userShare.setInviterId(inviter.getId()); // 邀请人ID
							userShare.setRegistrationTime(new Date()); // 注册时间
							userShare.setCreateBy(inviter);
							
							userShareService.saveUserShare(userShare);
						}
						
						json.put("success", true);
					}
				}
				
			}
		}
				
		return json.toString();
	}
	
	/**
	 * 发送短信验证码
	 * @param phone
	 * @return
	 * @throws JSONException
	 */
	@ResponseBody
	@RequestMapping(value = "sendMsg")
	public String sendMsg(@RequestParam(required=false) String phone) throws JSONException{
		
		JSONObject json = new JSONObject();
		
		if(phone == null || "".equals(phone)){
			json.put("success", false);
		} else {
			
			try {
				/**
				 * 通过审核的任一个应用的appkey
				 */
				String appkey = Constant.APP_KEY_MAP.get("1").toString();
				
				/**
				 * http://wiki.mob.com/smssdk2-0-web-api/
				 */
				// 发送手机验证码
				SmsWebApiKit apiKit = new SmsWebApiKit(appkey);
				String result = apiKit.sendMsg(phone, Constant.SMS_DEFAULT_ZONE); // 默认86
				
				if(result != null && !"".equals(result)){
					
					JSONObject obj = new JSONObject(result);
					int status = (Integer) obj.get("status");
					
					if(status == 200){
						json.put("success", true);
					} else {
						logger.info("验证码发送失败，错误代码为："+status+"，错误描述为："+Constant.SMS_VERIFY_CODE_STATUS_MAP.get(status));
						json.put("success", false);
					}
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
				
		return json.toString();
	}
	
	/**
	 * APP下载
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "download")
	public String appDownload(Model model) {
		
		return "mobile/modules/pay/download";
	}
	
	/**
	 * 获取公司信息
	 * @return
	 */
	private Office getCompany(){
		
		Office company = null;
		
		Office cofficeParam = new Office();
		cofficeParam.setType("1"); // 公司
		cofficeParam.setParentIds("0");
		
		List<Office> cofficeList = officeService.findList(cofficeParam);
		if(cofficeList != null && cofficeList.size() > 0){
			company = new Office(cofficeList.get(0).getId());
		} else {
			company = new Office("1");
		}
		
		return company;
	}
	
	/**
	 * 获取部门信息
	 * @return
	 */
	private Office getOffice(){
		
		Office office = null;
		
		Office oofficeParam = new Office();
		oofficeParam.setType("2"); // 部门
		oofficeParam.setParentIds("0");
		List<Office> oofficeList = officeService.findList(oofficeParam);
		if(oofficeList != null && oofficeList.size() > 0){
			office = new Office(oofficeList.get(0).getId());
		} else {
			office = new Office("2");
		}
		
		return office;
	}
	
	/**
	 * 获取角色列表
	 * @return
	 */
	private List<Role> getRoleListByEn(String enname){
		
		List<Role> roleList = Lists.newArrayList();
		
		Role roleParam = new Role();
		roleParam.setEnname(enname); // 普通用户
		roleList = systemService.findRole(roleParam);
		
		return roleList;
	}
	
	
	
}
